﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Configuration;
using Taobao.Top.Api.Util;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace Taobao.Common
{
    public class AuthorizationProvider
    {
        public static readonly AuthorizationProvider Current = new AuthorizationProvider();

        public AuthorizationResult Authorize(string shopName)
        {
            var currentIP = GetCurrentIP();// "220.194.54.85";// System.Net.Dns.GetHostName(); 
            var encoding = Encoding.Default;

            var sn = ConfigurationManager.AppSettings["sn"];
            var orderType = "tb";
            var requestUrlBuilder = new StringBuilder();
            requestUrlBuilder.Append("http://nettime.cn/tbsnCheck.asp?");
            requestUrlBuilder.AppendFormat("{0}={1}", "dpname", UrlEncode(shopName, encoding));
            requestUrlBuilder.AppendFormat("&{0}={1}", "sn", sn);
            requestUrlBuilder.AppendFormat("&{0}={1}", "ip", currentIP);
            requestUrlBuilder.AppendFormat("&{0}={1}", "ordertype", orderType);
              
            var req = (HttpWebRequest)WebRequest.Create(requestUrlBuilder.ToString());
            req.Method = "GET"; 
            var rsp = (HttpWebResponse)req.GetResponse();

            var response = WebUtils.GetResponseAsString(rsp, encoding);
            return GetPrepareResult(response); 
        }

        private AuthorizationResult GetPrepareResult(string resultString)
        {
            var result = new AuthorizationResult();
            try
            { 
                var serializer = new XmlSerializer(typeof(AuthorizationResult));
                var xReader = new StringReader(resultString);
                result = serializer.Deserialize(xReader) as AuthorizationResult;
            }
            catch(Exception e) { }
            return result;
        }

        private static string UrlEncode(string str, Encoding encoding)
        {
            StringBuilder sb = new StringBuilder();
            byte[] byStr = encoding.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
            for (int i = 0; i < byStr.Length; i++)
            {
                sb.Append(@"%" + Convert.ToString(byStr[i], 16));
            }

            return (sb.ToString());
        }

        private static string GetCurrentIP()
        {
            var url = "http://iframe.ip138.com/ic.asp";
            var req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "GET";
            var rsp = (HttpWebResponse)req.GetResponse();
            var encoding = Encoding.Default;
            var response = WebUtils.GetResponseAsString(rsp, encoding);

            var ipRegex = new Regex(@"\[((?:(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\]");
            var match = ipRegex.Match(response);
            return match != null && match.Success ? ipRegex.Match(response).Groups[1].Value : string.Empty;
        }
    }
    [Serializable]
    [XmlRoot("xmldoc")]
    public class AuthorizationResult
    {
        [XmlElement("status")]
        public string Status { get; set; }
        [XmlElement("info")]
        public string Info { get; set; }
        [XmlElement("ordertype")]
        public string OrderType { get; set; }
        [XmlElement("ip")]
        public string IP { get; set; }
        [XmlElement("dpname")]
        public string DPName { get; set; }
        [XmlElement("sn")]
        public string SN { get; set; }
    }
}
